package com.example.test.springdemo.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.test.springdemo.common.Result;
import com.example.test.springdemo.domain.AdToken;
import com.example.test.springdemo.domain.AdminUser;
import com.example.test.springdemo.domain.Roles;
import com.example.test.springdemo.service.AdminUserService;
import com.example.test.springdemo.service.LoginService;
import com.example.test.springdemo.util.JWTUtils;
import com.example.test.springdemo.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@RestController
@RequestMapping("/user")
@CrossOrigin //解决跨域注解
@Slf4j
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private AdminUserService adminUserService;


    @PostMapping("/login")
    public Result login(AdminUser adminUser,HttpServletRequest request){
        log.info("username:"+adminUser.getUsername());
        try{
            AdminUser user = loginService.findByUserName(adminUser);
            if (null == user){
                return Result.failure("此用户不存在");
            }
            //验证数据库密码与输入密码是否匹配
            boolean boolPwd = MD5Util.validPassword(adminUser.getPassword(), user.getPassword());
            if (adminUser.getUsername().equals(user.getUsername()) && boolPwd == true){
                Map<String,String> map =new HashMap<>();
                map.put("id",user.getId()+"");
                map.put("username",user.getUsername());

                String token = JWTUtils.getToken(map);
                AdToken adToken = new AdToken();
                adToken.setToken(token);

//                String phone = RemortIPUtils.getRemortIP(request);
//                System.out.println(phone);
//                user.setPhone(phone);
//                loginService.update(user);
                return Result.success("登录成功",adToken);
            }else{
                return Result.failure("用户名或密码错误");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.failure("服务器异常:"+e.getMessage());
        }
    }

    /**
     * 获取用户信息
     * @param request
     * @return
     */
    @GetMapping("/info")
    public Result info(HttpServletRequest request){
        try{
            String token = request.getHeader("token");
            System.out.println(token);
            AdminUser adminUser = new AdminUser();
            DecodedJWT verify = JWTUtils.verify(token);
            log.info("id->{}",verify.getClaim("id").asString());
            log.info("username->{}",verify.getClaim("username").asString());
            Roles user = new Roles();
            user.setRoles(verify.getClaim("username").asString());
            user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            user.setName("Super Admin");
            user.setIntroduction("I am a super administrator");
            return Result.success(user);
        }catch (Exception e){
            e.printStackTrace();
            return Result.failure("服务器错误:"+e.getMessage());
        }
    }

    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    public Result logout(){
        return Result.success("退出成功");
    }

    /**
     * 查询所有用户信息
     * @return
     */
    @GetMapping("/getAllUserInfo")
    public Result getAllUserInfo(){
        AdminUser user = new AdminUser();
        List<AdminUser> adminUserList = adminUserService.getAllUser(user);
        return Result.success(adminUserList);
    }


    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/delUser/{id}")
    public Result delUser(@PathVariable("id") Long id){
        System.out.println(id);
        adminUserService.deleteUser(id);
        return Result.success("删除成功");
    }

    /**
     * 根据用户id查询
     * @return
     */
    @GetMapping("/findByAdminUserId/{id}")
    public Result findByAdminUserId(@PathVariable("id") Long id) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        AdminUser adminUser = loginService.findByUserId(id);
        return Result.success(adminUser);
    }

    /**
     * 添加用户
     * @param adminUser
     * @return
     */
    @PostMapping("/insertOrUpdate")
    public Result insertOrUpdate(AdminUser adminUser,HttpServletRequest request){
        try {
            //获取token
            String token = request.getHeader("token");
            DecodedJWT verify = JWTUtils.verify(token);
            //获取登录用户
            String loginName = verify.getClaim("username").asString();
            //通过MD5给密码加密
            String encryptedPwd = MD5Util.getEncryptedPwd(adminUser.getPassword());
            adminUser.setPassword(encryptedPwd);
            AdminUser adUser = loginService.findByUserId(adminUser.getId());
            if (null != adUser){
                adminUser.setGmtModifyUser(loginName);
                adminUser.setGmtModifyTime(new Date());
                int update = adminUserService.update(adminUser);
                if (update > 0){
                    return Result.success("修改成功");
                }else{
                    return Result.success("修改失败");
                }
            }
            AdminUser user = new AdminUser();
            user.setUsername(adminUser.getUsername());
            AdminUser admin = loginService.findByUserName(user);
            if (admin != null){
                return Result.failure("该账号已存在");
            }
            adminUser.setGmtCreateUser(loginName);
            adminUser.setGmtCreateTime(new Date());
            adminUserService.insert(adminUser);
            return Result.success("添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.failure("服务器异常:"+e.getMessage());
        }

    }


    /**
     * 修改用户信息
     * @return
     */
    @PostMapping("/update")
    public Result  update(AdminUser adminUser){
        adminUserService.update(adminUser);
        return Result.success("修改成功");
    }

    /**
     * 根据用户名查询
     * @param username
     * @return
     */
    @GetMapping("/findByUserName")
    public Result findByUserName(String username){
        try {
            AdminUser adminUser = new AdminUser();
            if (null != username && !"".equals(username)){
                adminUser.setUsername(username);
            }
            List<AdminUser> adminUserList = adminUserService.getAllUser(adminUser);
            return Result.success(adminUserList);
        } catch (Exception e){
            e.printStackTrace();
            return Result.failure("服务器异常:"+e.getMessage());
        }
    }
}
